package com.bdth.controller;

import com.bdth.model.*;
import com.bdth.service.IDepartmentService;
import com.bdth.service.IDeviceBindService;
import com.bdth.service.IDeviceService;
import com.bdth.utils.HtmlUtil;
import com.bdth.utils.SessionUtils;
import com.bdth.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author: 徐斌
 * @Date: 2018-08-20 16:30
 */
@Controller
@RequestMapping("/deviceBind")
public class DeviceBindController extends BaseController {

	protected static final Logger logger = LoggerFactory.getLogger(DeviceBindController.class);

	private Boolean updateNode = false;

	@Autowired
	private IDepartmentService departmentService;

	@Autowired
	private IDeviceService deviceService;

	@Autowired
	private IDeviceBindService deviceBindService;

	Map<Integer, Department> depMap = new HashMap<Integer, Department>();

	private List<ZTreeNode> zTreeNodeList = new ArrayList<ZTreeNode>();

	/**
	 * 首页
	 *
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request)
			throws Exception {
		return forword("/deviceBind/deviceBindList");
	}

	@RequestMapping("/deviceBindView")
	public ModelAndView deviceBindView(HttpServletRequest request)
			throws Exception {
		return forword("/deviceBind/deviceBind");
	}


	/**
	 * json 列表页面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dataList")
	public void dataList(PageModel pageModel, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String equipName = request.getParameter("equipName");
		String simNo = request.getParameter("simNo");
		String parentSim = request.getParameter("parentSim");
		String depIdSearch = "" + request.getParameter("depIdSearch");
		String bindState = request.getParameter("bindState");
		map.put("equipName", equipName);
		map.put("simNo", simNo);
		map.put("parentSim", parentSim);
		map.put("typeID", 0);
		map.put("bindState", bindState);
		User user = SessionUtils.getUser(request);
		if (!StringUtil.isEmptyWithNullStr(depIdSearch) && !"0".equals(depIdSearch)) {
			List<Integer> depIds = getDepIds(Integer.valueOf(depIdSearch));
			map.put("depIds", depIds);
		} else {
			List<Integer> depIds = getDepIds(user.getDepId());
			map.put("depIds", depIds);
		}


		//紧跟着的第一个查询方法会被分页
		PageHelper.startPage(pageModel.getPage(), pageModel.getRows());
		List<Map> dataList = deviceBindService.queryMapDataByMapList(map);
		//获得结果集条总数
		PageInfo pageList = new PageInfo(dataList);
		//设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", pageList.getTotal());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}


	// 生成设备树菜单
	@RequestMapping("/getDeviceTree")
	public void getDeviceTree(HttpServletRequest request, HttpServletResponse response, Boolean updateNode) {
		this.updateNode = updateNode;
		zTreeNodeList.clear();
		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			Map<String, Object> mapDep = new HashMap<String, Object>();
			User user = SessionUtils.getUser(request);

			List<Integer> depIds = getDepIds(user.getDepId());
			mapDep.put("depIds", depIds);

			// 用户分配的车队
			List<Department> depSet = departmentService.queryByMapList(mapDep);
			List<Department> depList = new ArrayList<Department>();

			Map<Integer, Integer> nodeMap = new HashMap<Integer, Integer>();
			if (depSet != null) {
				for (Department dep : depSet) {
					depList.add(dep);
				}
			}

			List<Department> allDepList = departmentService.queryByMapList(new HashMap());

			for (Object obj : allDepList) {
				Department dep = (Department) obj;
				depMap.put(dep.getId(), dep);
			}
			createDeviceTreeNode(request);// 创建设备树节点
			// 生成部门树
		/*	Collections.sort(depList, new Comparator<Department>() {
				public int compare(Department o1, Department o2) {
					if (o1.getDepName() == null)
						return -1;

					return o1.getDepName().compareTo(o2.getDepName());
				}

			});*/
			for (Department d : depList) {
				Department dep = depMap.get(d.getId());
				if (dep == null)
					continue;
				setTreeData(dep, request);
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		resultMap.put("TreeDataIndex", zTreeNodeList);
		HtmlUtil.writerJson(response, resultMap);
	}


	/**
	 * 创建设备树节点
	 */
	private void createDeviceTreeNode(HttpServletRequest request) throws Exception {
		String path = request.getContextPath();
		Date start = new Date();
		Map<String, Object> params = new HashMap<String, Object>();
		User user = SessionUtils.getUser(request);
		List result = null;
		//params.put("userId", user.getId());
		List<Integer> depIds = getDepIds(user.getDepId());
		params.put("depIds", depIds);
		params.put("typeID", 0);
		result = deviceService.queryDeviceTree(params);
		if (result == null)
			result = new ArrayList();

		for (Object obj : result) {
			Map rowData = (Map) obj;
			String simNo = "" + rowData.get("SimNo");
			int vehicleId = (Integer) rowData.get("id");
			int depId = (Integer) rowData.get("DepId");
			String equipName = "" + rowData.get("equipName");
			String tid = "v" + vehicleId;
			String parentNodeId = "dep" + depId;
			ZTreeNode mzTn = new ZTreeNode(tid, equipName, parentNodeId, path + "/images/device.png", simNo);

			zTreeNodeList.add(mzTn);

			Department dep = depMap.get(depId);
			while (dep != null) {
				dep.setTotalNum(dep.getTotalNum() + 1);
				dep = depMap.get(dep.getParentDepId());
			}

		}
		Date end = new Date();

		//log.error("实时数据刷新耗时:" + seconds + ",条数：" + result.size());
	}

	private void setTreeData(Department dep, HttpServletRequest request) {
		String path = request.getContextPath();
		try {
			String depNodeId = "dep" + dep.getId();
			int parentId = dep.getParentDepId();
			// parentId = parentId > 0 ? ("dep_"+parentId) : 1;
			String strParentNodeId = "dep" + parentId;
			ZTreeNode mzTn = new ZTreeNode(depNodeId, dep.getDepName(),
					strParentNodeId, path + "/images/ztree/dep.png", false);

			zTreeNodeList.add(mzTn);

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}


	@RequestMapping("/deviceBind")
	public void deviceBind(String[] simNos, String parentSim, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		User user = SessionUtils.getUser(request);
		for (String simNo : simNos) {
			//查找CommandCard中数据
			CommandCard commandCard = deviceBindService.getCommandCardBySimNo(simNo);
			if (commandCard != null) {
				sendFailureMessage(response, "勾选设备存在已绑定指挥卡，请先解绑");
				return;
			}
		}

		deviceBindService.add(user, simNos, parentSim);
		sendSuccessMessage(response, "绑定成功");

	}


	@RequestMapping("/deviceUnBind")
	public void deviceUnBind(Integer[] bindIds, String parentSim, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		for (int bindId : bindIds) {
			CommandCard commandCard = new CommandCard();
			commandCard.setId(bindId);
			commandCard.setDeleted(1);
			deviceBindService.deleteFake(commandCard);
			sendSuccessMessage(response, "解绑成功");
		}
	}
}
